<template>
  <div class="plan-metrics-charts-container">
    <!-- 图表类型选择 -->
    <div class="chart-selector">
      <el-radio-group v-model="activeChartType" size="small">
        <el-radio-button label="overview">综合对比</el-radio-button>
        <el-radio-button label="utilization">设备利用率</el-radio-button>
        <el-radio-button label="capacity">产能分析</el-radio-button>
        <el-radio-button label="delivery">交期分析</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 图表容器 -->
    <div class="charts-content">
      <!-- 综合对比视图 -->
      <div v-show="activeChartType === 'overview'" class="chart-grid">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="card-title">交期完成率对比</span>
                  <el-icon><TrendCharts /></el-icon>
                </div>
              </template>
              <div ref="deliveryRateChartRef" class="chart-box"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="card-title">设备利用率对比</span>
                  <el-icon><Odometer /></el-icon>
                </div>
              </template>
              <div ref="utilizationChartRef" class="chart-box"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="card-title">实际产能对比</span>
                  <el-icon><Histogram /></el-icon>
                </div>
              </template>
              <div ref="capacityChartRef" class="chart-box"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="card-title">平均工时对比</span>
                  <el-icon><Timer /></el-icon>
                </div>
              </template>
              <div ref="workTimeChartRef" class="chart-box"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 设备利用率详细视图 -->
      <div v-show="activeChartType === 'utilization'" class="chart-full">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">设备利用率时间趋势</span>
              <el-tag type="info" size="small">按时间段统计</el-tag>
            </div>
          </template>
          <div ref="utilizationDetailChartRef" class="chart-box-large"></div>
        </el-card>
      </div>

      <!-- 产能分析详细视图 -->
      <div v-show="activeChartType === 'capacity'" class="chart-full">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">产能分布分析</span>
              <el-tag type="info" size="small">各设备产能对比</el-tag>
            </div>
          </template>
          <div ref="capacityDetailChartRef" class="chart-box-large"></div>
        </el-card>
      </div>

      <!-- 交期分析详细视图 -->
      <div v-show="activeChartType === 'delivery'" class="chart-full">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">交期完成情况分析</span>
              <el-tag type="info" size="small">订单交期统计</el-tag>
            </div>
          </template>
          <div ref="deliveryDetailChartRef" class="chart-box-large"></div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { TrendCharts, Odometer, Histogram, Timer } from '@element-plus/icons-vue'

export default {
  name: 'PlanMetricsCharts',
  components: {
    TrendCharts,
    Odometer,
    Histogram,
    Timer
  },
  props: {
    // 指标数据（包含多个方案的指标）
    metricsData: {
      type: Array,
      required: true,
      default: () => []
    },
    // 当前选中的约束 ID
    selectedConstraintId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    // 当前激活的图表类型
    const activeChartType = ref('overview')

    // 图表 DOM 引用
    const deliveryRateChartRef = ref(null)
    const utilizationChartRef = ref(null)
    const capacityChartRef = ref(null)
    const workTimeChartRef = ref(null)
    const utilizationDetailChartRef = ref(null)
    const capacityDetailChartRef = ref(null)
    const deliveryDetailChartRef = ref(null)

    // ECharts 实例
    let deliveryRateChart = null
    let utilizationChart = null
    let capacityChart = null
    let workTimeChart = null
    let utilizationDetailChart = null
    let capacityDetailChart = null
    let deliveryDetailChart = null

    /**
     * 初始化所有图表
     */
    const initCharts = () => {
      nextTick(() => {
        // 初始化综合对比图表
        initDeliveryRateChart()
        initUtilizationChart()
        initCapacityChart()
        initWorkTimeChart()

        // 初始化详细视图图表
        initUtilizationDetailChart()
        initCapacityDetailChart()
        initDeliveryDetailChart()

        // 监听窗口大小变化
        window.addEventListener('resize', handleResize)
      })
    }

    /**
     * 初始化交期完成率对比图表
     */
    const initDeliveryRateChart = () => {
      if (!deliveryRateChartRef.value) return

      deliveryRateChart = echarts.init(deliveryRateChartRef.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: getMockPlanNames(),
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '交期完成率',
            type: 'bar',
            data: getMockDeliveryRates(),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#67c23a' },
                { offset: 1, color: '#85ce61' }
              ])
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}%'
            }
          }
        ]
      }

      deliveryRateChart.setOption(option)
    }

    /**
     * 初始化设备利用率对比图表
     */
    const initUtilizationChart = () => {
      if (!utilizationChartRef.value) return

      utilizationChart = echarts.init(utilizationChartRef.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}%'
        },
        legend: {
          bottom: 10,
          left: 'center'
        },
        series: [
          {
            name: '设备利用率',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}\n{d}%'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            data: getMockUtilizationData()
          }
        ]
      }

      utilizationChart.setOption(option)
    }

    /**
     * 初始化实际产能对比图表
     */
    const initCapacityChart = () => {
      if (!capacityChartRef.value) return

      capacityChart = echarts.init(capacityChartRef.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: getMockPlanNames()
        },
        yAxis: {
          type: 'value',
          name: '产能'
        },
        series: [
          {
            name: '实际产能',
            type: 'bar',
            data: getMockCapacityData(),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#409eff' },
                { offset: 1, color: '#66b1ff' }
              ])
            },
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }

      capacityChart.setOption(option)
    }

    /**
     * 初始化平均工时对比图表
     */
    const initWorkTimeChart = () => {
      if (!workTimeChartRef.value) return

      workTimeChart = echarts.init(workTimeChartRef.value)
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: getMockPlanNames()
        },
        yAxis: {
          type: 'value',
          name: '工时(h)'
        },
        series: [
          {
            name: '平均工时',
            type: 'line',
            data: getMockWorkTimeData(),
            smooth: true,
            itemStyle: {
              color: '#e6a23c'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
                { offset: 1, color: 'rgba(230, 162, 60, 0.05)' }
              ])
            },
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }

      workTimeChart.setOption(option)
    }

    /**
     * 初始化设备利用率详细图表
     */
    const initUtilizationDetailChart = () => {
      if (!utilizationDetailChartRef.value) return

      utilizationDetailChart = echarts.init(utilizationDetailChartRef.value)
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: getMockPlanNames(),
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: getMockTimeSlots()
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: getMockPlanNames().map((name, index) => ({
          name,
          type: 'line',
          smooth: true,
          data: getMockUtilizationTrendData(),
          itemStyle: {
            color: getChartColor(index)
          }
        }))
      }

      utilizationDetailChart.setOption(option)
    }

    /**
     * 初始化产能详细图表
     */
    const initCapacityDetailChart = () => {
      if (!capacityDetailChartRef.value) return

      capacityDetailChart = echarts.init(capacityDetailChartRef.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: getMockPlanNames(),
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          data: getMockDeviceNames()
        },
        yAxis: {
          type: 'value',
          name: '产能'
        },
        series: getMockPlanNames().map((name, index) => ({
          name,
          type: 'bar',
          data: getMockDeviceCapacityData(),
          itemStyle: {
            color: getChartColor(index)
          }
        }))
      }

      capacityDetailChart.setOption(option)
    }

    /**
     * 初始化交期详细图表
     */
    const initDeliveryDetailChart = () => {
      if (!deliveryDetailChartRef.value) return

      deliveryDetailChart = echarts.init(deliveryDetailChartRef.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['按时交付', '延期交付', '提前交付'],
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          data: getMockPlanNames()
        },
        yAxis: {
          type: 'value',
          name: '订单数量'
        },
        series: [
          {
            name: '按时交付',
            type: 'bar',
            stack: 'total',
            data: [45, 50, 48, 52],
            itemStyle: { color: '#67c23a' }
          },
          {
            name: '延期交付',
            type: 'bar',
            stack: 'total',
            data: [5, 3, 4, 2],
            itemStyle: { color: '#f56c6c' }
          },
          {
            name: '提前交付',
            type: 'bar',
            stack: 'total',
            data: [10, 12, 13, 11],
            itemStyle: { color: '#409eff' }
          }
        ]
      }

      deliveryDetailChart.setOption(option)
    }

    /**
     * 获取图表颜色
     */
    const getChartColor = (index) => {
      const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399']
      return colors[index % colors.length]
    }

    /**
     * 处理窗口大小变化
     */
    const handleResize = () => {
      deliveryRateChart?.resize()
      utilizationChart?.resize()
      capacityChart?.resize()
      workTimeChart?.resize()
      utilizationDetailChart?.resize()
      capacityDetailChart?.resize()
      deliveryDetailChart?.resize()
    }

    /**
     * 销毁所有图表
     */
    const disposeCharts = () => {
      deliveryRateChart?.dispose()
      utilizationChart?.dispose()
      capacityChart?.dispose()
      workTimeChart?.dispose()
      utilizationDetailChart?.dispose()
      capacityDetailChart?.dispose()
      deliveryDetailChart?.dispose()
      
      window.removeEventListener('resize', handleResize)
    }

    // ============== 模拟数据生成函数 ==============

    const getMockPlanNames = () => ['方案1', '方案2', '方案3', '方案4']
    
    const getMockDeliveryRates = () => [95.5, 92.3, 97.8, 94.6]
    
    const getMockUtilizationData = () => [
      { value: 87.3, name: '方案1' },
      { value: 85.6, name: '方案2' },
      { value: 89.2, name: '方案3' },
      { value: 86.8, name: '方案4' }
    ]
    
    const getMockCapacityData = () => [1200, 1150, 1280, 1220]
    
    const getMockWorkTimeData = () => [6.5, 7.2, 6.8, 7.0]
    
    const getMockTimeSlots = () => ['08:00', '10:00', '12:00', '14:00', '16:00', '18:00']
    
    const getMockUtilizationTrendData = () => [75, 82, 88, 85, 90, 87]
    
    const getMockDeviceNames = () => ['设备1', '设备2', '设备3', '设备4', '设备5']
    
    const getMockDeviceCapacityData = () => [220, 190, 240, 210, 200]

    // 监听数据变化
    watch(() => props.metricsData, () => {
      nextTick(() => {
        // 数据变化时重新渲染图表
        initCharts()
      })
    }, { deep: true })

    onMounted(() => {
      initCharts()
    })

    onBeforeUnmount(() => {
      disposeCharts()
    })

    return {
      activeChartType,
      deliveryRateChartRef,
      utilizationChartRef,
      capacityChartRef,
      workTimeChartRef,
      utilizationDetailChartRef,
      capacityDetailChartRef,
      deliveryDetailChartRef
    }
  }
}
</script>

<style scoped>
.plan-metrics-charts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-selector {
  display: flex;
  justify-content: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.charts-content {
  min-height: 400px;
}

.chart-grid,
.chart-full {
  width: 100%;
}

.chart-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-box {
  width: 100%;
  height: 300px;
}

.chart-box-large {
  width: 100%;
  height: 500px;
}
</style>

